package com.my.blog.website.controller.admin;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableList;
import com.my.blog.website.constant.WebConst;
import com.my.blog.website.controller.BaseController;
import com.my.blog.website.dto.Types;
import com.my.blog.website.modal.Bo.RestResponseBo;
import com.my.blog.website.modal.Bo.UploadBo;
import com.my.blog.website.modal.Vo.UploadVo;
import com.my.blog.website.modal.Vo.UserVo;
import com.my.blog.website.service.ILogService;
import com.my.blog.website.service.IUploadService;
import com.my.blog.website.utils.Commons;
import com.my.blog.website.utils.DateKit;
import com.my.blog.website.utils.TaleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 附件管理
 * <p>
 * Created by 13 on 2017/2/21.
 */
@Controller
@RequestMapping("admin/upload")
public class FileUploadController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);

    public static final String CLASSPATH = TaleUtils.getUplodFilePath();

    @Resource
    private IUploadService uploadService;

    @Resource
    private ILogService logService;

    /**
     * 附件页面,只显示当天上传的文件
     *
     * @param request
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "")
    public String index(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "limit", defaultValue = "12") int limit) {
        UserVo user = this.user(request);
        PageInfo<UploadVo> uploadPaginator = uploadService.getTodayUploads(user.getUid(), page,limit);
        request.setAttribute("uploads", uploadPaginator);
        request.setAttribute(Types.UPLOAD_BASE_PATH.getType(), Commons.site_option(Types.UPLOAD_BASE_PATH.getType(), Commons.site_url()));
        request.setAttribute("max_file_size", WebConst.MAX_FILE_SIZE / 1024);
        return "admin/upload";
    }

    /**
     * 上传文件接口
     *
     * @param request
     * @return
     */
    @PostMapping(value = "save")
    @ResponseBody
    public RestResponseBo upload(HttpServletRequest request, @RequestParam("file") MultipartFile[] multipartFiles) throws IOException {
        UserVo users = this.user(request);
        Integer uid = users.getUid();
        List<String> errorFiles = new ArrayList<>();
        try {
            for (MultipartFile multipartFile : multipartFiles) {
                String fname = multipartFile.getOriginalFilename();
                if (multipartFile.getSize() <= WebConst.MAX_FILE_SIZE) {

                    // 子目录路径
                    String subPath = DateKit.dateFormat(new Date(), "yyyy/MM");

                    // 生成保存文件的相对路径
                    String fkey = TaleUtils.getUploadFileKey(Commons.getUploadBasePath(),subPath,fname);

                    List<String> videos = ImmutableList.of("mp4","avi","wma","mov","mkv","rmvb");
                    String extName = fname.substring(fname.lastIndexOf(".")+1,fname.length());
                    if(videos.contains(extName)){
                        extName = "video";
                    }

                    String ftype = TaleUtils.isImage(multipartFile.getInputStream()) ? Types.IMAGE.getType() : extName;
                    File file = new File(Commons.getUploadBasePath() + File.separator + fkey);
                    try {

                        FileCopyUtils.copy(multipartFile.getInputStream(), new FileOutputStream(file));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    UploadVo uploadVo = new UploadVo();
                    uploadVo.setFname(fname);
                    uploadVo.setFkey(fkey);
                    uploadVo.setFtype(ftype);
                    uploadVo.setSize(multipartFile.getSize());
                    uploadVo.setAuthorId(uid);
                    uploadVo.setSubPath(subPath);

                    uploadService.save(uploadVo);
                } else {
                    errorFiles.add(fname);
                }
            }
        } catch (Exception e) {
            return RestResponseBo.fail();
        }
        return RestResponseBo.ok(errorFiles);
    }

    /**
     * 上传文件接口
     *
     * @param request
     * @return
     */
    @PostMapping(value = "saveForArticle")
    @ResponseBody
    public RestResponseBo uploadForArticle(HttpServletRequest request, @RequestParam("file") MultipartFile[] multipartFiles) throws IOException {
        UserVo users = this.user(request);
        Integer uid = users.getUid();
        List<String> errorFiles = new ArrayList<>();
        String mdCode = null;
        try {
            for (MultipartFile multipartFile : multipartFiles) {
                String fname = multipartFile.getOriginalFilename();
                if (multipartFile.getSize() <= WebConst.MAX_FILE_SIZE) {

                    // 子目录路径
                    String subPath = DateKit.dateFormat(new Date(), "yyyy/MM");

                    // 生成保存文件的相对路径
                    String fkey = TaleUtils.getUploadFileKey(Commons.getUploadBasePath(),subPath,fname);
                    String ftype = TaleUtils.isImage(multipartFile.getInputStream()) ? Types.IMAGE.getType() : Types.FILE.getType();
                    File file = new File(Commons.getUploadBasePath() + File.separator + fkey);
                    try {

                        FileCopyUtils.copy(multipartFile.getInputStream(), new FileOutputStream(file));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    UploadVo uploadVo = new UploadVo();
                    uploadVo.setFname(fname);
                    uploadVo.setFkey(fkey);
                    uploadVo.setFtype(ftype);
                    uploadVo.setSize(multipartFile.getSize());
                    uploadVo.setAuthorId(uid);
                    uploadVo.setSubPath(subPath);

                    uploadService.save(uploadVo);

                    mdCode = Commons.recoveryFileUrlForMd(uploadVo.getMarkdownCode(),request);
                } else {
                    errorFiles.add(fname);
                }
            }
        } catch (Exception e) {
            return RestResponseBo.fail();
        }

        Object data = mdCode==null?errorFiles:mdCode;
        return RestResponseBo.ok(data);
    }


    /**
     * 删除文件
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "delete")
    @ResponseBody
    public RestResponseBo delete(@RequestParam Long id, HttpServletRequest request) {
        try {
            UploadVo uploadVo = uploadService.selectById(id);
            if (null == uploadVo) {
                return RestResponseBo.fail("不存在该附件");
            }

            uploadVo.setDelFlag(Boolean.TRUE);
            uploadService.update(uploadVo);

            // 没有 真正删除文件
            //new File(CLASSPATH + uploadVo.getFkey()).delete();
            //logService.insertLog(LogActions.DEL_ARTICLE.getAction(), attach.getFkey(), request.getRemoteAddr(), this.getUid(request));
        } catch (Exception e) {
            String msg = "附件删除失败";
            LOGGER.error(msg, e);
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }

    /**
     * 根据条件获取列表
     *
     * @param request
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "list")
    public String list(HttpServletRequest request, String subPath,String ftype,String keyword,String delFlag,Integer page,Integer limit) {
        UserVo user = this.user(request);
        PageInfo<UploadVo> uploadPaginator = uploadService.getListByCondition(user.getUid(), subPath,ftype,keyword,delFlag, page, limit);
        request.setAttribute("uploads", uploadPaginator);
        request.setAttribute(Types.UPLOAD_BASE_PATH.getType(), Commons.site_option(Types.UPLOAD_BASE_PATH.getType(), Commons.site_url()));
        request.setAttribute("uploadBo", new UploadBo(subPath,ftype,keyword,delFlag));
        return "admin/upload_list";
    }

    @GetMapping(value = "edit/{id}")
    public String toEditPage(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            UploadVo uploadVo = uploadService.selectById(id);
            if (null == uploadVo) {
                LOGGER.error("id={}的附件不存在",id);
            }

            request.setAttribute("upload", uploadVo);

        } catch (Exception e) {
            String msg = "id={}的附件获取失败";
            LOGGER.error(msg, id);
        }

        return "admin/upload_edit";
    }

    /**
     * 更新文件信息
     *
     * @param uploadVo
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "modify")
    @ResponseBody
    public RestResponseBo update(UploadVo uploadVo, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (null != uploadVo || null == uploadVo.getId()) {
                uploadService.update(uploadVo);
                return RestResponseBo.ok();
            }
        } catch (Exception e) {
        }

        String msg = "更新失败";
        LOGGER.error(msg);
        return RestResponseBo.fail(msg);
    }

}
